package com.home766.util;

import net.biz.util.JsonUtils;
import org.apache.commons.lang.StringEscapeUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
	
	public static String replaceVariable(String template, Map<String, String> map) throws Exception {
		Pattern regex = Pattern.compile("\\{(.*?)\\}");
		Matcher regexMatcher = regex.matcher(template);
		while (regexMatcher.find()) {
			String key = regexMatcher.group(1);
			String toReplace = regexMatcher.group(0);
			String value = (String) map.get(key);
			if (value != null)
				template = template.replace(toReplace, value);
			else {
				throw new Exception(new StringBuilder().append("没有找到[").append(key).append("]对应的变量值，请检查表变量配置!").toString());
			}
		}
		return template;
	}
	/**
     * 判断一个字符串是不是空或者为"",{ },[ ]
     * @param s
     * @return
     */
    public static boolean isNullOrSpace(String s){
        if(null == s || s.length() == 0||"{}".equals(s)||"[]".equals(s)){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 删除掉JSON串前后的[]，某些插件不能解析带[]的json格式
     * @param json
     * @return
     */
    public static String treatJson(String json){
        if(null == json || json.length() < 3){
            return "";
        }
        json = json.substring(1, json.length());
        json = json.substring(0, json.length()-1);
        return json;
    }
    /**
     * 提供字符串是否可转换成数值型的判断
     * 如果可转成数值，则返回false
     * 如果不可转成数值，则返回true
     * isnan == is not a number
     * @param s 需要测试的字符串
     * @return  true or false
     */
    public static boolean isNAN(String s){
        if(null == s || s.length() == 0){
            return true;
        }
        Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+$");
        Matcher isNum = pattern.matcher(s);
        if(isNum.matches()){
            return false;
        }else{
            return true;
        }
    }
    /**
     * 如果传过来个空，则返回"" 
     * 否则返回原对象
     * @param o
     * @return
     */
    public static Object nullToSpace(Object o){
        if(null == o){
            return "";
        }
        return o;
    }
    /**
     * 解决GET方式乱码问题
     * @param s
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encode(String s) throws UnsupportedEncodingException {
        if(null == s || s.length() == 0){
            return "";
        }
        s = new String(s.getBytes("iso-8859-1"),"UTF-8");
        return s;
    }
    /**
     * 验证某字符串是否符合手机格式
     * @param str
     * @return
     */
    public static boolean isMobile(String str){
        String regular = "1\\d{10}";
        Pattern pattern = Pattern.compile(regular);
        boolean flag = false;
        if (str != null) {
            Matcher matcher = pattern.matcher(str);
            flag = matcher.matches();
        }
        return flag;
    }
    /**
     * 将字符串转移为ASCII码
     * @param cnStr
     * @return
     */
    public static String getCnASCII(String cnStr) {
        StringBuffer strBuf = new StringBuffer();
        byte[] bGBK = cnStr.getBytes();
        for (int i = 0; i < bGBK.length; i++) {
            strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
        }
        return strBuf.toString();
    }
    /**
     * unicode 转中文
     * @param utfString
     * @return
     */
    public static String convertUnicode(String utfString){
	    StringBuilder sb = new StringBuilder();
	    int i = -1;  
	    int pos = 0;  
	    while((i=utfString.indexOf("\\u", pos)) != -1){  
	        sb.append(utfString.substring(pos, i));  
	        if(i+5 < utfString.length()){  
	            pos = i+6;  
	            sb.append((char) Integer.parseInt(utfString.substring(i+2, i+6), 16));
	        }  
	    }  
	    return sb.toString();  
	}
    
    /**
     * 判断字符串是否是数字
     * @param str
     * @return
     */
    public static boolean isNumber(String str){
    	String rex = "^[+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$";
    	return str.matches(rex);
    }
    /**
     * 判断对象是否为空
     * 
     * @param str
     * @return
     */
    public static boolean isNotEmpty(Object str) {
        boolean flag = true;
        if (str != null && !str.equals("") && !str.equals("undefined")) {
            if (str.toString().length() > 0) {
                flag = true;
            }
        } else {
            flag = false;
        }
        return flag;
    }
    /**
     * 去json中的多余的引号
     * @param info
     * @return
     */
    public static String jsonString(String info){
    	return StringEscapeUtils.unescapeHtml(info);
    }
    public enum StringType{
    	FIRSTEND,
    	ALL,
    	OTHER
    }
    public static String trim(String str, StringType type){
    	if(!isNullOrSpace(str)){
    		if(type!=null){
        		switch (type) {
        		case FIRSTEND:
        			str=str.trim();
        			break;
        		case ALL:
        			str=str.replaceAll(" ", "");
        			break;
        		default:
        			str=str.replaceAll("\\s*", "");
        			break;
        		}
        	}else{
        		str=str.trim();
        	}
    	}
    	return str;
    }
    public static BigDecimal valiBigDecimal(BigDecimal decimal){
    	decimal.toString();
    	String str=decimal.toString();
    	if(!str.matches("^([0-9]*)+(.[0-9]{1})?$")){
    		decimal=decimal.divide(new BigDecimal(10));
    		return decimal;
    	}
    	return null;
    }
    public static Map<String, String> convertJson(String json){
    	if(!isNullOrSpace(json)){
    		Map<String, String> result= JsonUtils.toObject(json, Map.class);
    		return result;
    	}
		return null;
	}
    public static int getCharacterSetLength(String str){
    	char[] t1 = null;
    	t1 = str.toCharArray();
        int t0 = t1.length;
        int count = 0;
        for (int i = 0; i < t0; i++) {
	       if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
	    	   count+=2;
	       }else{
	    	   count++;
	       }
        }
        return count;
    }
//    public static List<CartItem> comparatorList(List<CartItem> cartItems){
//    	Comparator<CartItem> cmp = new Comparator<CartItem>() {
//
//            public int compare(CartItem o1, CartItem o2) {
//                Comparator<Object> cmp = Collator.getInstance(java.util.Locale.CHINA);
//                return  cmp.compare(o1.getItemName(), o2.getItemName());
//            }
//        };
//        Collections.sort(cartItems, cmp);
//        return cartItems;
//    }
}
